<template>
  <view class="container">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading">
      <uni-load-more status="loading" :content-text="loadingText"></uni-load-more>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="error" class="error">
      <text class="error-text">{{ error }}</text>
      <button class="retry-btn" @click="loadData">{{ $t('common.retry') }}</button>
    </view>

    <!-- 数据展示 -->
    <view v-else-if="reportData" class="report-content">
      <!-- 悬浮下载按钮 -->
      <view class="floating-download-btn" @click="downloadReport">
        <text class="download-text">{{ $t('report.download_report') }}</text>
      </view>

      <!-- 悬浮历史记录按钮 -->
      <view class="floating-history-btn" @click="goToHistory">
        <text class="history-text">{{ $t('report.history_record') }}</text>
      </view>

      <!-- 舌诊信息 -->
      <view v-if="reportData.tongue_info" class="section">
        <view class="section-header" @click="toggleSection('tongue')">
          <text class="section-title">{{ $t('report.tongue_info') }}</text>
          <view class="collapse-icon" :class="{ 'collapsed': collapsedSections.tongue }">
            <text class="icon-text">{{ collapsedSections.tongue ? '▲' : '▼' }}</text>
          </view>
        </view>
        <view v-show="!collapsedSections.tongue" class="section-content">
        <view class="tongue-info">
          <!-- 舌诊图片 -->
          <view v-if="reportData.tongue_info.tongue_front_img || reportData.tongue_info.tongue_bottom_img" class="tongue-images">
            <view v-if="reportData.tongue_info.tongue_front_img" class="tongue-image-container">
              <text class="image-label">{{ $t('report.tongue_front') }}</text>
              <image 
                :src="reportData.tongue_info.tongue_front_img" 
                mode="aspectFit" 
                class="tongue-image"
                @error="handleImageError"
              ></image>
            </view>
            <view v-if="reportData.tongue_info.tongue_bottom_img" class="tongue-image-container">
              <text class="image-label">{{ $t('report.tongue_bottom') }}</text>
              <image 
                :src="reportData.tongue_info.tongue_bottom_img" 
                mode="aspectFit" 
                class="tongue-image"
                @error="handleImageError"
              ></image>
            </view>
          </view>

          <!-- 诊断结果 -->
          <view v-if="reportData.tongue_info.result" class="diagnosis-item">
            <text class="diagnosis-title">{{ $t('report.tongue_result') }}</text>
            <text class="diagnosis-content">{{ reportData.tongue_info.result }}</text>
          </view>

          <view v-if="reportData.tongue_info.explanation" class="diagnosis-item">
            <text class="diagnosis-title">{{ $t('report.tongue_explanation') }}</text>
            <text class="diagnosis-content">{{ reportData.tongue_info.explanation }}</text>
          </view>

          <!-- 舌色信息 -->
          <view v-if="reportData.tongue_info.tonguecolour_type" class="diagnosis-item">
            <text class="diagnosis-title">{{ $t('report.tongue_colour') }}</text>
            <text class="diagnosis-content">{{ reportData.tongue_info.tonguecolour_type }}</text>
            <text v-if="reportData.tongue_info.tonguecolour_explain" class="diagnosis-detail">{{ reportData.tongue_info.tonguecolour_explain }}</text>
          </view>

          <!-- 舌苔色信息 -->
          <view v-if="reportData.tongue_info.tonguefurcolour_type" class="diagnosis-item">
            <text class="diagnosis-title">{{ $t('report.tongue_fur_colour') }}</text>
            <text class="diagnosis-content">{{ reportData.tongue_info.tonguefurcolour_type }}</text>
            <text v-if="reportData.tongue_info.tonguefurcolour_explain" class="diagnosis-detail">{{ reportData.tongue_info.tonguefurcolour_explain }}</text>
          </view>

          <!-- 舌形和苔质信息 -->
          <view v-if="reportData.tongue_info.tongueShape && reportData.tongue_info.tongueShape.length > 0" class="tongue-shape">
            <!-- 苔质信息 -->
            <view v-if="getTongueShapeByType(1).length > 0" class="shape-group">
              <text class="diagnosis-title">{{ $t('report.tongue_coating') }}</text>
              <view v-for="(shape, index) in getTongueShapeByType(1)" :key="index" class="shape-item">
                <text class="shape-type">{{ shape.type || '-' }}</text>
                <text class="shape-explain">{{ shape.explain || '-' }}</text>
              </view>
            </view>
            
            <!-- 舌型信息 -->
            <view v-if="getTongueShapeByType(2).length > 0" class="shape-group">
              <text class="diagnosis-title">{{ $t('report.tongue_shape') }}</text>
              <view v-for="(shape, index) in getTongueShapeByType(2)" :key="index" class="shape-item">
                <text class="shape-type">{{ shape.type || '-' }}</text>
                <text class="shape-explain">{{ shape.explain || '-' }}</text>
              </view>
            </view>
          </view>

          <!-- 舌下脉络诊断 -->
          <view v-if="reportData.tongue_info.sub_diag_project" class="diagnosis-item">
            <text class="diagnosis-title">{{ $t('report.sub_diag_project') }}</text>
            <text class="diagnosis-content">{{ reportData.tongue_info.sub_diag_project }}</text>
            <text v-if="reportData.tongue_info.sub_diag_project_detail" class="diagnosis-detail">{{ reportData.tongue_info.sub_diag_project_detail }}</text>
          </view>
        </view>
        </view>
      </view>

      <!-- 面诊信息 -->
      <view v-if="reportData.face_info" class="section">
        <view class="section-header" @click="toggleSection('face')">
          <text class="section-title">{{ $t('report.face_info') }}</text>
          <view class="collapse-icon" :class="{ 'collapsed': collapsedSections.face }">
            <text class="icon-text">{{ collapsedSections.face ? '▲' : '▼' }}</text>
          </view>
        </view>
        <view v-show="!collapsedSections.face" class="section-content">
        <view class="face-info">
          <!-- 面部图片 -->
          <view v-if="reportData.face_info.face_img_path || reportData.face_info.face_left_img_path || reportData.face_info.face_right_img_path" class="face-images">
            <view v-if="reportData.face_info.face_img_path" class="face-image-container">
              <text class="image-label">{{ $t('report.face_front') }}</text>
              <image 
                :src="reportData.face_info.face_img_path" 
                mode="aspectFit" 
                class="face-image"
                @error="handleImageError"
              ></image>
            </view>
            <view v-if="reportData.face_info.face_left_img_path" class="face-image-container">
              <text class="image-label">{{ $t('report.face_left') }}</text>
              <image 
                :src="reportData.face_info.face_left_img_path" 
                mode="aspectFit" 
                class="face-image"
                @error="handleImageError"
              ></image>
            </view>
            <view v-if="reportData.face_info.face_right_img_path" class="face-image-container">
              <text class="image-label">{{ $t('report.face_right') }}</text>
              <image 
                :src="reportData.face_info.face_right_img_path" 
                mode="aspectFit" 
                class="face-image"
                @error="handleImageError"
              ></image>
            </view>
          </view>

          <!-- 面色诊断 -->
          <view v-if="reportData.face_info.complexion_result" class="diagnosis-item">
            <text class="diagnosis-title">{{ $t('report.complexion_result') }}</text>
            <text class="diagnosis-content">{{ reportData.face_info.complexion_result }}</text>
          </view>

          <view v-if="reportData.face_info.complexion_detail" class="diagnosis-item">
            <text class="diagnosis-title">{{ $t('report.complexion_detail') }}</text>
            <text class="diagnosis-content">{{ reportData.face_info.complexion_detail }}</text>
          </view>

          <view v-if="reportData.face_info.complexion_affecting_organ" class="diagnosis-item">
            <text class="diagnosis-title">{{ $t('report.complexion_affecting_organ') }}</text>
            <text class="diagnosis-content">{{ reportData.face_info.complexion_affecting_organ }}</text>
          </view>

          <view v-if="reportData.face_info.complexion_diagnostic_analysis" class="diagnosis-item">
            <text class="diagnosis-title">{{ $t('report.complexion_diagnostic_analysis') }}</text>
            <text class="diagnosis-content">{{ reportData.face_info.complexion_diagnostic_analysis }}</text>
          </view>

          <view v-if="reportData.face_info.complexion_illness_hazard" class="diagnosis-item">
            <text class="diagnosis-title">{{ $t('report.complexion_illness_hazard') }}</text>
            <text class="diagnosis-content">{{ reportData.face_info.complexion_illness_hazard }}</text>
          </view>

          <view v-if="reportData.face_info.complexion_base_explain" class="diagnosis-item">
            <text class="diagnosis-title">{{ $t('report.complexion_base_explain') }}</text>
            <text class="diagnosis-content">{{ reportData.face_info.complexion_base_explain }}</text>
          </view>

          <!-- 眼部诊断 -->
          <view v-if="reportData.face_info.eye_result" class="diagnosis-item">
            <text class="diagnosis-title">{{ $t('report.eye_result') }}</text>
            <text class="diagnosis-content">{{ reportData.face_info.eye_result }}</text>
          </view>

          <view v-if="reportData.face_info.eye_diagnostic_analysis" class="diagnosis-item">
            <text class="diagnosis-title">{{ $t('report.eye_diagnostic_analysis') }}</text>
            <text class="diagnosis-content">{{ reportData.face_info.eye_diagnostic_analysis }}</text>
          </view>

          <view v-if="reportData.face_info.eye_bag_diagnostic_analysis" class="diagnosis-item">
            <text class="diagnosis-title">{{ $t('report.eye_bag_diagnostic_analysis') }}</text>
            <text class="diagnosis-content">{{ reportData.face_info.eye_bag_diagnostic_analysis }}</text>
          </view>

          <view v-if="reportData.face_info.eye_related_hazards" class="diagnosis-item">
            <text class="diagnosis-title">{{ $t('report.eye_related_hazards') }}</text>
            <text class="diagnosis-content">{{ reportData.face_info.eye_related_hazards }}</text>
          </view>
        </view>
        </view>
      </view>

      <!-- 脉象信息 -->
      <view v-if="reportData.pulse_info" class="section">
        <view class="section-header" @click="toggleSection('pulse')">
          <text class="section-title">{{ $t('report.pulse_info') }}</text>
          <view class="collapse-icon" :class="{ 'collapsed': collapsedSections.pulse }">
            <text class="icon-text">{{ collapsedSections.pulse ? '▲' : '▼' }}</text>
          </view>
        </view>
        <view v-show="!collapsedSections.pulse" class="section-content">
        <view class="pulse-info">
          <!-- 脉象图表 -->
          <view v-if="reportData.pulse_info" class="pulse-charts">
            <!-- 左右手脉象图表 Tab -->
            <view class="tabs-container">
              <view
                class="tab-button"
                :class="{ active: activePulseHandTab === 'left' }"
                v-if="hasLeftPulseData"
                @click="activePulseHandTab = 'left'">
                {{ $t('report.left_pulse') }}
              </view>
              <view
                class="tab-button"
                :class="{ active: activePulseHandTab === 'right' }"
                v-if="hasRightPulseData"
                @click="activePulseHandTab = 'right'">
                {{ $t('report.right_pulse') }}
              </view>
            </view>

            <!-- 寸关尺脉象图表 -->
            <view class="chart-wrapper" v-if="activePulseHandTab === 'left' && hasLeftPulseData">
              <BaseCharts :option="pulseChartOptionLeft" />
            </view>
            <view class="chart-wrapper" v-if="activePulseHandTab === 'right' && hasRightPulseData">
              <BaseCharts :option="pulseChartOptionRight" />
            </view>
          </view>

          <!-- 脉象类型标签 -->
          <view class="pulse-result-box" v-if="reportData.pulse_info.left_pulse_info.details && reportData.pulse_info.left_pulse_info.details.length > 0">
            <view class="tabs-container">
              <view
                v-for="(pulse, index) in pulseTypes"
                :key="index"
                class="tab-button"
                :class="{ active: activeTabIndex === index }"
                @click="setActiveTab(index)">
                {{ pulse.label }}<text class="tab-value">{{ pulse.value }}</text>
              </view>
            </view>

            <!-- 脉象详情描述 -->
            <view class="details-container">
              <text class="details-text">{{ activePulseDetail }}</text>
            </view>
          </view>
        </view>
        </view>
      </view>

      <!-- 调理建议（富文本展示） -->
      <view v-if="reportData.pulse_info && reportData.pulse_info.left_pulse_info.details && reportData.pulse_info.left_pulse_info.details.length > 0" class="section">
        <view class="section-header" @click="toggleSection('suggest')">
          <text class="section-title">{{ $t('report.pulse_suggest') }}</text>
          <view class="collapse-icon" :class="{ 'collapsed': collapsedSections.suggest }">
            <text class="icon-text">{{ collapsedSections.suggest ? '▲' : '▼' }}</text>
          </view>
        </view>
        <view v-show="!collapsedSections.suggest" class="section-content">
        <view class="suggest-content">
          <rich-text v-if="firstPulseSuggest" :nodes="firstPulseSuggest" @error="handleRichTextError"></rich-text>
          <text v-else class="no-suggest-text">{{ $t('report.no_suggest') }}</text>
        </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { createDiagnoseReport, getDiagnoseReport, getPDFFile } from '@/api/order'
import BaseCharts from '../blue/BaseCharts.vue'

const { t, locale } = useI18n()

// 响应式数据
const loading = ref(true)
const error = ref('')
const reportData = ref(null)
const activeTabIndex = ref(0)
const activePulseHandTab = ref('left')


// 折叠状态管理
const collapsedSections = ref({
  tongue: false,    // 舌诊信息
  face: false,      // 面诊信息
  pulse: false,     // 脉诊信息
  suggest: false    // 调理建议
})

// 加载文本配置
const loadingText = {
  contentdown: t('common.pull_down_refresh'),
  contentrefresh: t('common.refreshing'),
  contentnomore: t('common.no_more_data')
}

// 加载数据
const loadData = async () => {
  loading.value = true
  error.value = ''
  // console.log("locale", locale.value)
  
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options || {}
  const reportId = options.id
  
  // console.log('页面参数:', options)
  // console.log('报告ID:', reportId)
  
  try {
    let response
    
    if (reportId) {
      // 从列表页跳转过来，调用查看详情接口
      // console.log('从列表页跳转，调用查看详情接口')
      response = await getDiagnoseReport(reportId)
    } else {
      // 直接访问页面，调用创建报告接口
      // console.log('直接访问页面，调用创建报告接口')
      response = await createDiagnoseReport()
    }
    
    // console.log('API响应:', response)
    
    if (response.code === 200) {
      reportData.value = response.result
    } else {
      // 处理特定的错误情况
      if (response.code === 400 && response.message) {
        // 显示具体的错误信息
        uni.showModal({
          title: t('report.no_data_title'),
          content: response.message,
          showCancel: false,
          confirmText: t('common.confirm'),
          success: () => {
            // 返回上一页
            if (reportId) {
              uni.navigateBack()
            } else {
              uni.switchTab({
                url: '/pages/index/index'
              })
            }
          }
        })
      } else {
        // 其他错误情况
        uni.showModal({
          title: t('report.load_failed'),
          content: response.message || t('report.load_error'),
          showCancel: false,
          confirmText: t('common.confirm'),
          success: () => {
            // 返回上一页
            if (reportId) {
              uni.navigateBack()
            } else {
              uni.switchTab({
                url: '/pages/index/index'
              })
            }
          }
        })
      }
    }
  } catch (err) {
    console.error('加载报告数据失败:', err)
    uni.showModal({
      title: t('report.load_failed'),
      content: t('report.load_error'),
      showCancel: false,
      confirmText: t('common.confirm'),
      success: () => {
        // 返回上一页
        if (reportId) {
          uni.navigateBack()
        } else {
          uni.switchTab({
            url: '/pages/index/index'
          })
        }
      }
    })
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  
  try {
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (e) {
    return dateString
  }
}


// 根据data_type获取舌形信息
const getTongueShapeByType = (dataType) => {
  if (!reportData.value?.tongue_info?.tongueShape) {
    return []
  }
  return reportData.value.tongue_info.tongueShape.filter(item => item.data_type === dataType)
}

// 左右手数据可用性
const hasLeftPulseData = computed(() => !!reportData.value?.pulse_info?.left_pulse_info)
const hasRightPulseData = computed(() => !!reportData.value?.pulse_info?.right_pulse_info)

// 当数据加载后，设置默认显示的手部 Tab
watch(() => reportData.value?.pulse_info, () => {
  if (hasLeftPulseData.value) {
    activePulseHandTab.value = 'left'
  } else if (hasRightPulseData.value) {
    activePulseHandTab.value = 'right'
  }
})

// 构建脉象图表配置（寸、关、尺三线）
const buildPulseChartOption = (pulseSideInfo) => {
  if (!pulseSideInfo) return null

  const cunData = pulseSideInfo.cun_data || []
  const guanData = pulseSideInfo.guan_data || []
  const chiData = pulseSideInfo.chi_data || []

  const maxLength = Math.max(cunData.length, guanData.length, chiData.length)
  const xAxisData = Array.from({ length: maxLength }, (_, i) => i + 1)

  const allData = [...cunData, ...guanData, ...chiData]
  if (allData.length === 0) return null
  const dataMin = Math.min(...allData)
  const dataMax = Math.max(...allData)
  const yMin = Math.floor(dataMin / 20) * 20 - 20
  const yMax = Math.ceil(dataMax / 20) * 20 + 20

  return {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#ddd',
      borderWidth: 1,
      textStyle: {
        color: '#333',
        fontSize: 12
      },
      formatter: function(params) {
        let result = `<div style="font-weight: bold; margin-bottom: 8px;">${t('report.pulse_info')}</div>`
        params.forEach(param => {
          result += `<div style="display: flex; justify-content: space-between; margin: 4px 0;">
            <span style=\"color: ${param.color}; margin-right: 10px;\">●</span>
            <span style=\"margin-right: 10px;\">${param.seriesName}:</span>
            <span style=\"font-weight: bold;\">${param.value}</span>
          </div>`
        })
        return result
      }
    },
    legend: {
      data: [
        { name: t('blueIndex.legendCun'), icon: 'circle' },
        { name: t('blueIndex.legendGuan'), icon: 'circle' },
        { name: t('blueIndex.legendChi'), icon: 'circle' }
      ],
      top: '5%',
      left: 'center',
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        fontSize: 12,
        color: '#333'
      },
      itemGap: 30
    },
    grid: { 
      left: '13%', 
      right: '5%', 
      bottom: '10%', 
      top: '25%',
      containLabel: false
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData,
      axisLine: { 
        lineStyle: { color: '#ccc', width: 1 } 
      },
      axisTick: { 
        show: true, 
        alignWithLabel: true,
        lineStyle: { color: '#ccc' }
      },
      axisLabel: {
        interval: (index, value) => index % Math.ceil(maxLength / 10) === 0,
        color: '#666',
        fontSize: 10
      }
    },
    yAxis: {
      type: 'value',
      min: yMin,
      max: yMax,
      interval: Math.ceil((yMax - yMin) / 6),
      axisLine: { 
        show: true, 
        lineStyle: { color: '#ccc', width: 1 } 
      },
      axisTick: {
        lineStyle: { color: '#ccc' }
      },
      axisLabel: {
        color: '#666',
        fontSize: 10
      },
      splitLine: { 
        show: false
      }
    },
    series: [
      {
        name: t('blueIndex.legendCun'),
        type: 'line',
        smooth: true,
        smoothMonotone: 'x',
        showSymbol: false,
        symbol: 'none',
        symbolSize: 0,
        data: cunData,
        lineStyle: { color: '#ff4757', width: 1.5 },
        itemStyle: { color: '#ff4757' },
        emphasis: {
          focus: 'series',
          lineStyle: { width: 2.0 },
          showSymbol: false,
          symbol: 'none',
          symbolSize: 0
        },
        animationDuration: 2000,
        animationEasing: 'cubicOut'
      },
      {
        name: t('blueIndex.legendGuan'),
        type: 'line',
        smooth: true,
        smoothMonotone: 'x',
        showSymbol: false,
        symbol: 'none',
        symbolSize: 0,
        data: guanData,
        lineStyle: { color: '#3742fa', width: 1.5 },
        itemStyle: { color: '#3742fa' },
        emphasis: {
          focus: 'series',
          lineStyle: { width: 2.0 },
          showSymbol: false,
          symbol: 'none',
          symbolSize: 0
        },
        animationDuration: 2000,
        animationEasing: 'cubicOut'
      },
      {
        name: t('blueIndex.legendChi'),
        type: 'line',
        smooth: true,
        smoothMonotone: 'x',
        showSymbol: false,
        symbol: 'none',
        symbolSize: 0,
        data: chiData,
        lineStyle: { color: '#2ed573', width: 1.5 },
        itemStyle: { color: '#2ed573' },
        emphasis: {
          focus: 'series',
          lineStyle: { width: 2.0 },
          showSymbol: false,
          symbol: 'none',
          symbolSize: 0
        },
        animationDuration: 2000,
        animationEasing: 'cubicOut'
      }
    ]
  }
}

const pulseChartOptionLeft = computed(() => {
  if (!hasLeftPulseData.value) return null
  return buildPulseChartOption(reportData.value.pulse_info.left_pulse_info)
})

const pulseChartOptionRight = computed(() => {
  if (!hasRightPulseData.value) return null
  return buildPulseChartOption(reportData.value.pulse_info.right_pulse_info)
})

// 提取脉象类型用于渲染标签
const pulseTypes = computed(() => {
  if (!reportData.value?.pulse_info?.left_pulse_info.details) {
    return []
  }

  return reportData.value.pulse_info.left_pulse_info.details.map(detail => {
    const score = detail.score || detail.pulse_type
    const label = score.replace(/[0-9]/g, '') // 移除数字得到文字
    const value = score.replace(/[^0-9]/g, '') // 移除文字得到数字
    return {
      label: label,
      value: value
    }
  })
})

// 获取当前激活的脉象描述
const activePulseDetail = computed(() => {
  if (!reportData.value?.pulse_info?.left_pulse_info.details || activeTabIndex.value >= reportData.value.pulse_info.left_pulse_info.details.length) {
    return t('pulseAnalysis.noData')
  }
  return reportData.value.pulse_info.left_pulse_info.details[activeTabIndex.value].pulse_condition
})

// 切换tab的方法
const setActiveTab = (index) => {
  activeTabIndex.value = index
}

// 清理HTML内容，移除Office特有的标签
const cleanHtml = (html) => {
  if (!html) return ''
  
  return html
    // 移除Office特有的标签
    .replace(/<o:[^>]*>/g, '')
    .replace(/<\/o:[^>]*>/g, '')
    // 移除Word特有的注释
    .replace(/<!--\[if[^>]*>.*?<!\[endif\]-->/g, '')
    // 移除MsoNormal类名，保留p标签
    .replace(/class="MsoNormal"/g, '')
    // 移除font标签，保留内容
    .replace(/<font[^>]*>/g, '')
    .replace(/<\/font>/g, '')
    // 移除span标签，保留内容
    .replace(/<span[^>]*>/g, '')
    .replace(/<\/span>/g, '')
    // 移除b标签，保留内容
    .replace(/<b[^>]*>/g, '<strong>')
    .replace(/<\/b>/g, '</strong>')
    // 移除h3标签，保留内容
    .replace(/<h3[^>]*>/g, '<h3>')
    .replace(/<\/h3>/g, '</h3>')
    // 清理多余的空白字符
    .replace(/\s+/g, ' ')
    // 清理多余的换行
    .replace(/\n+/g, '\n')
    // 确保HTML结构完整
    .replace(/<p[^>]*>\s*<\/p>/g, '') // 移除空段落
    .trim()
}

// 获取第一个脉象建议（富文本）
const firstPulseSuggest = computed(() => {
//   console.log('firstPulseSuggest computed:', reportData.value?.pulse_info?.details)
  if (!reportData.value?.pulse_info?.left_pulse_info.details || reportData.value.pulse_info.left_pulse_info.details.length === 0) {
    // console.log('No pulse details found')
    return null
  }
  const suggest = reportData.value.pulse_info.left_pulse_info.details[0].pulse_suggest
  
  // 清理HTML内容
  const cleanedSuggest = cleanHtml(suggest)
  
  return cleanedSuggest
})

// 处理富文本渲染错误
const handleRichTextError = (error) => {
  console.error('Rich text rendering error:', error)
  // 如果富文本渲染失败，可以尝试显示纯文本
  uni.showToast({
    title: t('report.render_error'),
    icon: 'none',
    duration: 2000
  })
}

// 切换折叠状态
const toggleSection = (sectionKey) => {
  collapsedSections.value[sectionKey] = !collapsedSections.value[sectionKey]
}

// 下载报告功能
const downloadReport = () => {
  // 检查网络连接
  uni.getNetworkType({
    success: (res) => {
      // console.log('网络状态:', res)
      if (res.networkType === 'none') {
        uni.showToast({
          title: locale.value === 'zh' ? '请检查网络连接' : 'Please check network connection',
          icon: 'none'
        })
        return
      }
      
      // 显示加载提示
      uni.showLoading({
        title: t('common.loading'),
        mask: true
      })
      
      // 调用PDF获取API
      // console.log('开始调用PDF获取API...')
      // console.log('当前语言:', locale.value)
      getPDFFile(reportData.value.id)
        .then((response) => {
          // console.log('PDF获取响应:', response)
          uni.hideLoading()
          
          if (response && response.code === 200 && response.result) {
            // 获取PDF文件URL
            const pdfUrl = response.result
            
            // 检查是否为有效URL
            if (typeof pdfUrl === 'string' && pdfUrl.startsWith('http')) {
              // 处理PDF文件打开
              handlePDFOpen(pdfUrl)
            } else {
              throw new Error('无效的PDF文件URL')
            }
          } else {
            throw new Error(response?.message || '获取PDF文件失败')
          }
        })
        .catch((error) => {
          uni.hideLoading()
          console.error('API调用失败:', error)
          
          // 根据错误代码提供更具体的错误信息
          let errorMessage = locale.value === 'zh' ? '服务暂时不可用' : 'Service temporarily unavailable'
          let showRetry = false
          
          if (error.code === 401) {
            errorMessage = locale.value === 'zh' ? '请先登录' : 'Please login first'
          } else if (error.code === 'TIMEOUT') {
            errorMessage = locale.value === 'zh' ? '请求超时，请检查网络连接' : 'Request timeout, please check network connection'
            showRetry = true
          } else if (error.code === 'NETWORK_ERROR') {
            errorMessage = locale.value === 'zh' ? '网络连接失败，请重试' : 'Network connection failed, please retry'
            showRetry = true
          } else if (error.code === 'HTTP_ERROR') {
            errorMessage = locale.value === 'zh' ? '服务器错误，请稍后重试' : 'Server error, please try again later'
            showRetry = true
          } else if (error.message && error.message.includes('无效的PDF文件URL')) {
            errorMessage = locale.value === 'zh' ? 'PDF文件地址无效' : 'Invalid PDF file URL'
            showRetry = true
          } else if (error.message && error.message.includes('获取PDF文件失败')) {
            errorMessage = locale.value === 'zh' ? '获取PDF文件失败，请重试' : 'Failed to get PDF file, please retry'
            showRetry = true
          }
          
          if (showRetry) {
            // 显示重试对话框
            uni.showModal({
              title: locale.value === 'zh' ? '获取失败' : 'Failed to Get',
              content: errorMessage,
              confirmText: locale.value === 'zh' ? '重试' : 'Retry',
              cancelText: locale.value === 'zh' ? '取消' : 'Cancel',
              success: (res) => {
                if (res.confirm) {
                  // 用户选择重试
                  setTimeout(() => {
                    downloadReport()
                  }, 1000) // 延迟1秒后重试
                }
              }
            })
          } else {
            // 显示普通错误提示
            uni.showToast({
              title: errorMessage,
              icon: 'none',
              duration: 3000
            })
          }
        })
    },
    fail: () => {
      uni.showToast({
        title: locale.value === 'zh' ? '网络状态检查失败' : 'Network status check failed',
        icon: 'none'
      })
    }
  })
}

// 处理PDF文件打开
const handlePDFOpen = (pdfUrl) => {
  // console.log('处理PDF文件打开:', pdfUrl)
  
  // 检测平台
  const systemInfo = uni.getSystemInfoSync()
  const platform = systemInfo.platform
  
  // 生成时间戳用于文件名
  const now = new Date()
  const dateStr = now.getFullYear() + 
    String(now.getMonth() + 1).padStart(2, '0') + 
    String(now.getDate()).padStart(2, '0') + '_' +
    String(now.getHours()).padStart(2, '0') + 
    String(now.getMinutes()).padStart(2, '0')
  
  const fileName = locale.value === 'zh' 
    ? `中医诊断报告_${dateStr}.pdf` 
    : `TCM_Diagnosis_Report_${dateStr}.pdf`
  
  if (platform === 'android') {
    // 安卓端处理 - 使用uni.downloadFile避免CORS问题
    // console.log('安卓端处理PDF下载和打开')
    
    uni.downloadFile({
      url: pdfUrl,
      success: (res) => {
        // console.log('PDF下载成功:', res)
        if (res.statusCode === 200) {
          // 尝试打开PDF文件
          uni.openDocument({
            filePath: res.tempFilePath,
            success: () => {
              // console.log('PDF文件打开成功')
              uni.showToast({
                title: locale.value === 'zh' ? '报告打开成功' : 'Report opened successfully',
                icon: 'success',
                duration: 2000
              })
            },
            fail: (err) => {
              console.error('PDF文件打开失败:', err)
              // 显示文件位置提示
              uni.showModal({
                title: locale.value === 'zh' ? '文件下载成功' : 'File downloaded successfully',
                content: locale.value === 'zh' 
                  ? 'PDF报告已下载到您的设备，请在文件管理器中查看' 
                  : 'PDF report has been downloaded to your device, please check in file manager',
                showCancel: false,
                confirmText: locale.value === 'zh' ? '知道了' : 'OK'
              })
            }
          })
        } else {
          throw new Error('PDF文件下载失败')
        }
      },
      fail: (err) => {
        console.error('PDF下载失败:', err)
        // 如果下载失败，尝试直接打开URL
        tryDirectOpen(pdfUrl, fileName)
      }
    })
  } else if (platform === 'ios') {
    // iOS端处理 - 使用uni.downloadFile避免CORS问题
    // console.log('iOS端处理PDF下载和打开')
    
    uni.downloadFile({
      url: pdfUrl,
      success: (res) => {
        // console.log('PDF下载成功:', res)
        if (res.statusCode === 200) {
          // 尝试打开PDF文件
          uni.openDocument({
            filePath: res.tempFilePath,
            success: () => {
              // console.log('PDF文件打开成功')
              uni.showToast({
                title: locale.value === 'zh' ? '报告打开成功' : 'Report opened successfully',
                icon: 'success',
                duration: 2000
              })
            },
            fail: (err) => {
              console.error('PDF文件打开失败:', err)
              // 显示文件位置提示
              uni.showModal({
                title: locale.value === 'zh' ? '文件下载成功' : 'File downloaded successfully',
                content: locale.value === 'zh' 
                  ? 'PDF报告已下载到您的设备，请在文件应用中查看' 
                  : 'PDF report has been downloaded to your device, please check in Files app',
                showCancel: false,
                confirmText: locale.value === 'zh' ? '知道了' : 'OK'
              })
            }
          })
        } else {
          throw new Error('PDF文件下载失败')
        }
      },
      fail: (err) => {
        console.error('PDF下载失败:', err)
        // 如果下载失败，尝试直接打开URL
        tryDirectOpen(pdfUrl, fileName)
      }
    })
  } else {
    // H5端处理 - 尝试多种方式避免CORS问题
    // console.log('H5端处理PDF打开')
    tryDirectOpen(pdfUrl, fileName)
  }
}

// 尝试直接打开PDF（H5端或作为备选方案）
const tryDirectOpen = (pdfUrl, fileName) => {
  // console.log('尝试直接打开PDF:', pdfUrl)
  
  // 检测是否为移动端Safari
  const isMobileSafari = /iPad|iPhone|iPod/.test(navigator.userAgent) && /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)
  
  // 方法1: 尝试使用fetch获取PDF并创建blob URL
  fetch(pdfUrl, {
    method: 'GET',
    mode: 'cors', // 尝试CORS
    credentials: 'include' // 包含认证信息
  })
  .then(response => {
    if (response.ok) {
      return response.blob()
    } else {
      throw new Error('PDF获取失败')
    }
  })
  .then(blob => {
    // 创建blob URL
    const blobUrl = window.URL.createObjectURL(blob)
    
    if (isMobileSafari) {
      // 移动端Safari特殊处理
      const a = document.createElement('a')
      a.href = blobUrl
      a.download = fileName
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      
      // 延迟清理blob URL
      setTimeout(() => {
        window.URL.revokeObjectURL(blobUrl)
      }, 1000)
      
      uni.showModal({
        title: locale.value === 'zh' ? '文件已下载' : 'File Downloaded',
        content: locale.value === 'zh' 
          ? 'PDF文件已下载到您的设备。请在"文件"应用中查看，或使用分享功能保存到其他位置。' 
          : 'PDF file has been downloaded to your device. Please check in the "Files" app or use the share function to save to other locations.',
        showCancel: false,
        confirmText: locale.value === 'zh' ? '知道了' : 'OK'
      })
    } else {
      // 桌面端浏览器 - 新窗口打开
      const newWindow = window.open(blobUrl, '_blank')
      
      if (newWindow) {
        try {
          newWindow.document.title = fileName
        } catch (e) {
          // console.log('无法设置窗口标题，这是正常的跨域限制')
        }
        
        // 监听窗口关闭事件，清理blob URL
        newWindow.onbeforeunload = () => {
          window.URL.revokeObjectURL(blobUrl)
        }
        
        uni.showToast({
          title: locale.value === 'zh' ? '报告打开成功' : 'Report opened successfully',
          icon: 'success',
          duration: 2000
        })
      } else {
        // 如果新窗口被阻止，回退到下载
        const a = document.createElement('a')
        a.href = blobUrl
        a.download = fileName
        a.style.display = 'none'
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        window.URL.revokeObjectURL(blobUrl)
        
        uni.showToast({
          title: locale.value === 'zh' ? '报告下载成功' : 'Report downloaded successfully',
          icon: 'success',
          duration: 2000
        })
      }
    }
  })
  .catch(error => {
    console.error('Fetch方式失败:', error)
    
    // 方法2: 如果fetch失败，尝试直接打开URL（可能被CORS阻止）
    // console.log('尝试直接打开URL（可能被CORS阻止）')
    
    if (isMobileSafari) {
      // 移动端Safari - 直接在新窗口打开
      const newWindow = window.open(pdfUrl, '_blank')
      
      if (newWindow) {
        uni.showToast({
          title: locale.value === 'zh' ? '报告打开成功' : 'Report opened successfully',
          icon: 'success',
          duration: 2000
        })
      } else {
        showCORSErrorMessage()
      }
    } else {
      // 桌面端浏览器 - 直接在新窗口打开
      const newWindow = window.open(pdfUrl, '_blank')
      
      if (newWindow) {
        try {
          newWindow.document.title = fileName
        } catch (e) {
          console.log('无法设置窗口标题，这是正常的跨域限制')
        }
        
        uni.showToast({
          title: locale.value === 'zh' ? '报告打开成功' : 'Report opened successfully',
          icon: 'success',
          duration: 2000
        })
      } else {
        showCORSErrorMessage()
      }
    }
  })
}

// 显示CORS错误信息
const showCORSErrorMessage = () => {
  uni.showModal({
    title: locale.value === 'zh' ? '打开失败' : 'Open Failed',
    content: locale.value === 'zh' 
      ? '由于浏览器安全限制，无法直接打开PDF文件。请尝试以下方法：\n\n1. 复制PDF链接到新标签页打开\n2. 使用移动端应用查看\n3. 联系管理员配置CORS策略' 
      : 'Due to browser security restrictions, the PDF file cannot be opened directly. Please try:\n\n1. Copy the PDF link and open in a new tab\n2. Use mobile app to view\n3. Contact administrator to configure CORS policy',
    showCancel: false,
    confirmText: locale.value === 'zh' ? '知道了' : 'OK'
  })
}

// 处理图片加载错误
const handleImageError = (e) => {
  console.error('图片加载失败:', e)
}

// 跳转到历史记录页面
const goToHistory = () => {
  uni.navigateTo({
    url: '/pages/record/report/index'
  })
}


// 监听语言变化，更新页面标题
watch(locale, () => {
  uni.setNavigationBarTitle({
    title: t('report.title')
  })
})

// 页面加载时获取数据
onMounted(() => {
  // 设置页面标题国际化
  uni.setNavigationBarTitle({
    title: t('report.title')
  })
  
  loadData()
})
</script>

<style lang="scss">
.container {
  padding: 15px;
  background-color: #6c5ff8;
  min-height: 100vh;
  position: relative;
}

.floating-download-btn {
  position: fixed;
  bottom: 30px;
  right: 20px;
  background-color: #1296db;
  color: white;
  padding: 12px 20px;
  border-radius: 25px;
  box-shadow: 0 4px 12px rgba(18, 150, 219, 0.3);
  z-index: 1000;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
    box-shadow: 0 2px 8px rgba(18, 150, 219, 0.4);
  }
  
  .download-text {
    font-size: 14px;
    font-weight: 500;
  }
}

.floating-history-btn {
  position: fixed;
  bottom: 90px;
  right: 20px;
  background-color: #6c5ff8;
  color: white;
  padding: 12px 20px;
  border-radius: 25px;
  box-shadow: 0 4px 12px rgba(108, 95, 248, 0.3);
  z-index: 1000;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
    box-shadow: 0 2px 8px rgba(108, 95, 248, 0.4);
  }
  
  .history-text {
    font-size: 14px;
    font-weight: 500;
  }
}

.floating-test-btn {
  position: fixed;
  bottom: 150px;
  right: 20px;
  background-color: #ff6b6b;
  color: white;
  padding: 12px 20px;
  border-radius: 25px;
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
  z-index: 1000;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.95);
    box-shadow: 0 2px 8px rgba(255, 107, 107, 0.4);
  }
  
  .test-text {
    font-size: 14px;
    font-weight: 500;
  }
}



.loading, .error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 20px;
}

.error-text {
  color: #ff4757;
  font-size: 16px;
  margin-bottom: 20px;
  text-align: center;
}

.retry-btn {
  background-color: #1296db;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  font-size: 14px;
}

.report-content {
  .report-header {
    background-color: white;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 15px;
    text-align: center;
    
    .report-title {
      font-size: 20px;
      font-weight: bold;
      color: #333;
      display: block;
      margin-bottom: 10px;
    }
    
    .report-date {
      font-size: 14px;
      color: #666;
    }
  }

  .section {
    background-color: white;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 15px;
    border: 1px solid #eee;
    
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #eee;
      padding-bottom: 10px;
      margin-bottom: 15px;
      cursor: pointer;
      user-select: none;
      
      .section-title {
        font-size: 18px;
        font-weight: bold;
        color: #333;
      }
      
      .collapse-icon {
        width: 24px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        background-color: #f5f5f5;
        transition: all 0.3s ease;
        
        .icon-text {
          font-size: 12px;
          color: #666;
          transition: transform 0.3s ease;
        }
        
        &.collapsed {
          .icon-text {
            transform: rotate(180deg);
          }
        }
        
        &:hover {
          background-color: #e9e9e9;
        }
      }
    }
    
    .section-content {
      transition: all 0.3s ease;
    }
  }

  .user-info {
    .info-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 0;
      border-bottom: 1px solid #f5f5f5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .label {
        color: #666;
        font-size: 14px;
      }
      
      .value {
        color: #333;
        font-size: 14px;
        font-weight: 500;
      }
    }
  }

  .pulse-info {
    .pulse-charts {
      margin-bottom: 20px;
      
      .chart-wrapper {
        height: 350px;
        width: 100%;
        background-color: #fff;
        border-radius: 10px;
        margin-bottom: 15px;
        padding: 5px;
        box-sizing: border-box;
        border: 1px solid #eee;
      }
    }
    
    .pulse-result-box {
      background-color: #fff;
      border-radius: 10px;
      margin-bottom: 20px;
      padding: 20px;
      border: 1px solid #eee;
    }

    .tabs-container {
      display: flex;
      justify-content: space-around;
      border-bottom: 2px solid #f0f0f0;
      padding-bottom: 15px;
      margin-bottom: 15px;
    }

    .tab-button {
      padding: 8px 12px;
      font-size: 14px;
      color: #888;
      border-radius: 6px;
      background-color: transparent;
      transition: all 0.3s;
      border-bottom: 4px solid transparent;
      font-weight: 500;
      cursor: pointer;

      &.active {
        color: #333;
        border-bottom-color: #4e7afb;
        font-weight: bold;
      }

      .tab-value {
        font-size: 12px;
        margin-left: 2px;
      }
    }

    .details-container {
      padding-top: 10px;

      .details-text {
        font-size: 14px;
        line-height: 1.6;
        color: #666;
        text-align: justify;
      }
    }
    
    .suggest-content {
      padding-top: 10px;
      
      :deep(p) {
        margin: 8px 0;
        line-height: 1.6;
        color: #333;
      }
      
      :deep(strong) {
        font-weight: bold;
        color: #1296db;
      }
      
      :deep(em) {
        font-style: italic;
        color: #666;
      }
      
      :deep(ul), :deep(ol) {
        margin: 8px 0;
        padding-left: 20px;
      }
      
      :deep(li) {
        margin: 4px 0;
        line-height: 1.5;
      }
      
      :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
        margin: 12px 0 8px 0;
        color: #333;
        font-weight: bold;
      }
      
      :deep(blockquote) {
        margin: 10px 0;
        padding: 10px 15px;
        background-color: #f8f9fa;
        border-left: 4px solid #1296db;
        border-radius: 4px;
      }
      
      :deep(code) {
        background-color: #f1f3f4;
        padding: 2px 6px;
        border-radius: 3px;
        font-family: 'Courier New', monospace;
        font-size: 12px;
      }
      
      :deep(a) {
        color: #1296db;
        text-decoration: none;
        
        &:hover {
          text-decoration: underline;
        }
      }
      
      .no-suggest-text {
        color: #999;
        font-style: italic;
        text-align: center;
        padding: 20px 0;
      }
    }
    
    .pulse-data {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 10px;
      
      .data-item {
        background-color: #f8f9fa;
        border-radius: 5px;
        padding: 10px;
        text-align: center;
        
        .data-label {
          display: block;
          font-size: 12px;
          color: #666;
          margin-bottom: 5px;
        }
        
        .data-value {
          display: block;
          font-size: 16px;
          font-weight: bold;
          color: #333;
        }
      }
    }
  }

  .face-info {
    .face-images {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 20px;
      
      .face-image-container {
        text-align: center;
        flex: 1;
        margin: 0 5px;
        
        &:first-child {
          margin-left: 0;
        }
        
        &:last-child {
          margin-right: 0;
        }
        
        .image-label {
          display: block;
          font-size: 12px;
          color: #666;
          margin-bottom: 10px;
        }
        
        .face-image {
          width: 100%;
          max-width: 120px;
          height: 120px;
          border-radius: 10px;
          border: 1px solid #eee;
        }
      }
    }
  }

  .tongue-info {
    .tongue-images {
      display: flex;
      justify-content: space-around;
      margin-bottom: 20px;
      
      .tongue-image-container {
        text-align: center;
        
        .image-label {
          display: block;
          font-size: 12px;
          color: #666;
          margin-bottom: 10px;
        }
        
        .tongue-image {
          width: 150px;
          height: 150px;
          border-radius: 10px;
          border: 1px solid #eee;
        }
      }
    }
    
    .tongue-shape {
      margin-top: 20px;
      
      .shape-group {
        margin-bottom: 20px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
      
      .shape-item {
        background-color: #f8f9fa;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 10px;
        
        .shape-type {
          display: block;
          font-size: 14px;
          font-weight: bold;
          color: #1296db;
          margin-bottom: 5px;
        }
        
        .shape-explain {
          display: block;
          font-size: 12px;
          color: #666;
        }
      }
    }
  }

  .diagnosis-item {
    margin-bottom: 20px;
    
    .diagnosis-title {
      display: block;
      font-size: 16px;
      font-weight: bold;
      color: #333;
      margin-bottom: 8px;
    }
    
    .diagnosis-content {
      display: block;
      font-size: 14px;
      color: #333;
      line-height: 1.6;
      margin-bottom: 5px;
    }
    
    .diagnosis-detail {
      display: block;
      font-size: 12px;
      color: #666;
      line-height: 1.5;
      font-style: italic;
    }
  }
}
</style>
